﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DCS.ComLib.Config;
using VietThuongLMS.Services;
using VietThuongLMS.ViewModels;
using VietThuongLMS.Utils;
using System.Web.Security;
using VietThuongLMS.Areas.Admin.Models;
using System.Text.RegularExpressions;

namespace VietThuongLMS.Areas.Admin.Controllers
{
    public class HocVienController : Controller
    {
        //attribute
        private LMSDataEntities context = new LMSDataEntities();

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult Index()
        {
            int page = 1;
            if (Request["p"] != null)
            {
                page = int.Parse(Request["p"].ToString());
            }

            TaiKhoan account = AccountService.GetTaiKhoanVaLoai(HttpContext.User.Identity.Name);
            HocVienViewModel hocVienList;
            if(account.MaLoaiTaiKhoan == "Admin")
                hocVienList = HocVienService.GetHocVienList(int.Parse(ConfigReader.ReadString("ItemPerPage")), page);
            else
                hocVienList = HocVienService.GetHocVienList(int.Parse(ConfigReader.ReadString("ItemPerPage")), page, HttpContext.User.Identity.Name);

            //phân trang
            Pagination pagination = new Pagination(true, Url.Content("~"), "Admin", "HocVien", "Index", "?p=", hocVienList.Total, page, int.Parse(ConfigReader.ReadString("ItemPerPage")), "Previous", "Next", "First", "End");
            string pageLinks = pagination.GetPageLinks();
            ViewData["pageLinks"] = pageLinks;
            //end phân trang

            //NHDuc added
            ViewData["page"] = (page - 1) * int.Parse(ConfigReader.ReadString("ItemPerPage")) + 1;
            //end NHDuc

            return View(hocVienList);
        }

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult Detail(int id)
        {
            //HocVien hv = HocVienService.GetHocVienById(id);
            HocVienDetailViewModel viewModel = new HocVienDetailViewModel();
            viewModel.hocVienModel = HocVienService.GetHocVienById(id);

            viewModel.hocVien_LopViewModel = context.HocVien_Lop.Join(context.LopHocs,
                hvl => hvl.MaLopHoc,
                l => l.ID,
                (hvl, l) => hvl).Join(context.HocViens,
                hvl => hvl.MaHocVien,
                hv => hv.ID,
                (hvl, hv) => hvl).Where(hvl => hvl.MaHocVien == id).FirstOrDefault();
            return View(viewModel);
        }

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult Create()
        {
            using (LMSDataEntities context = new LMSDataEntities())
            {
                HocVien hv = new HocVien();
                List<object> values = new List<object>();
                values.Add(new { ID = "choose", Name = "--Giới Tính--" });
                values.AddRange(from GioiTinh gioiTinh in Enum.GetValues(typeof(GioiTinh))
                                select new { ID = gioiTinh, Name = gioiTinh.ToString() });

                ViewData["sexes"] = new SelectList(values, "Id", "Name");
                IEnumerable<SelectListItem> maCN = new SelectList(context.ChiNhanhs.ToList(), "ID", "TenChiNhanh");
                ViewData["MaCN"] = maCN;

                //ViewData["CBRole"] = new SelectList(context.LoaiTaiKhoans.ToList(), "id", "name");
                return View();
            }
        }

        [Authorize(Roles = "Admin,NhanVien")]
        [HttpPost, ValidateInput(false)]
        public ActionResult Create(FormCollection collection)
        {
            HocVienModel model = new HocVienModel();
            if (ModelState.IsValid)
            {
                try
                {
                    // TODO: Add insert logic here
                    TaiKhoan tk = new TaiKhoan();

                    tk.MaTaiKhoan = collection["taiKhoan.UserName"].Trim();
                    //tk.MatKhau = FormsAuthentication.HashPasswordForStoringInConfigFile(collection["taiKhoan.Password"], "md5");
                    tk.MatKhau = FormsAuthentication.HashPasswordForStoringInConfigFile("123456", "md5");
                    tk.HoTen = collection["taiKhoan.FullName"];
                    tk.DiaChi = collection["taiKhoan.Address"];
                    tk.DienThoai = collection["taiKhoan.Phone"];
                    tk.Email = collection["taiKhoan.Email"];
                    tk.Deleted = Utils.Constant.INACTIVE;
                    tk.MaLoaiTaiKhoan = Utils.Constant.ACCOUNT_ROLE_STUDENT;
                    tk.NgayDangKy = DateTime.Today;
                    tk.GioiTinh = collection["taiKhoan.Sex"];
                    tk.NgheNghiep = collection["taiKhoan.Job"];
                    tk.NoiCongTac = collection["taiKhoan.Location_Job"];
                    tk.Deleted = Utils.Constant.INACTIVE;
                    Converter c = new Converter();
                    tk.NgaySinh = c.StringToDate(collection["taiKhoan.Birthday"]);

                    model.taiKhoan = new AccountModel();
                    model.taiKhoan.FullName = tk.HoTen;

                    bool result = AccountService.InsertAccount(tk);
                    if (result)
                    {
                        HocVien hv = new HocVien();
                        hv.MaTaiKhoan = tk.ID;
                        hv.Deleted = Utils.Constant.INACTIVE;
                        bool r = HocVienService.InsertHocVien(hv);
                        if (r)
                            return RedirectToAction("Index", "HocVien", new { area = "Admin" });
                    }
                    //using (LMSDataEntities context = new LMSDataEntities())
                    //{
                    //    ViewData["CBRole"] = new SelectList(context.LoaiTaiKhoans.ToList(), "id", "name");
                    //    return View(model);
                    //}
                    //return RedirectToAction("Create", "HocVien", new { area = "Admin" });
                    return View("Create", model);
                }
                catch (Exception ex)
                {
                    DCS.ComLib.File.Log.Write("HocVienController::Create", ex.StackTrace, ex.Message);
                    return View("Create", model);
                }
            }
            //Invalid, redisplay form with errors
            return View("Create", model);
        }

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult Edit(int id)
        {
            HocVien hv = HocVienService.GetHocVienById(id);

            List<object> values = new List<object>();
            values.Add(new { ID = "1", Name = "Chờ Duyệt" });
            values.Add(new { ID = "2", Name = "Chuẩn Bị Học" });
            values.Add(new { ID = "3", Name = "Đã Nghỉ" });

            ViewData["Deleted"] = new SelectList(values, "ID", "Name", (hv.Deleted != null ? hv.Deleted : 1));

            return View(hv);
        }

        [Authorize(Roles = "Admin,NhanVien")]
        [HttpPost, ValidateInput(false)]
        public ActionResult Edit(int id, FormCollection collection)
        {
            HocVien hv = HocVienService.GetHocVienById(id);

            // TODO: Add update logic here
            //bool result = ModelState.IsValidField(collection["TaiKhoan.Email"]);

            List<object> values = new List<object>();
            values.Add(new { ID = "1", Name = "Chờ Duyệt" });
            values.Add(new { ID = "2", Name = "Chuẩn Bị Học" });
            values.Add(new { ID = "3", Name = "Đã Nghĩ" });

            ViewData["Deleted"] = new SelectList(values, "ID", "Name");

            bool flag = true;

            if (collection["TaiKhoan.Email"].Length <= 0)
            {
                ModelState.AddModelError("TaiKhoan.Email", "(*) Email không được để trống");
                hv.TaiKhoanReference.Value.Email = collection["TaiKhoan.Email"];
                flag = false;
            }
            else
            {
                if (!Regex.IsMatch(collection["TaiKhoan.Email"], @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
                {
                    hv.TaiKhoanReference.Value.Email = collection["TaiKhoan.Email"];
                    ModelState.AddModelError("TaiKhoan.Email", "(*) Email không hợp lệ");
                    flag = false;
                }
            }

            if (collection["TaiKhoan.HoTen"].Length <= 0)
            {
                ModelState.AddModelError("TaiKhoan.HoTen", "(*) Họ tên không được để trống");
                hv.TaiKhoanReference.Value.HoTen = collection["TaiKhoan.HoTen"];
                flag = false;
            }
            if (collection["TaiKhoan.DienThoai"].Length <= 0)
            {
                ModelState.AddModelError("TaiKhoan.DienThoai", "(*) Số điện thoại không được để trống");
                hv.TaiKhoanReference.Value.DienThoai = collection["TaiKhoan.DienThoai"];
                flag = false;
            }
            
            if(flag){
                try
                {
                    
                    TaiKhoan tk = new TaiKhoan();

                    tk.HoTen = collection["TaiKhoan.HoTen"];
                    tk.DiaChi = collection["TaiKhoan.DiaChi"];
                    tk.DienThoai = collection["TaiKhoan.DienThoai"];
                    tk.Email = collection["TaiKhoan.Email"];
                    tk.GioiTinh = collection["TaiKhoan.GioiTinh"];
                    Converter c = new Converter();
                    tk.NgaySinh = c.StringToDate(collection["taiKhoan.Birthday"]);

                    tk.ID = (int)hv.MaTaiKhoan;
                    //if (collection["TaiKhoan.MatKhau"] != null)
                    //    tk.MatKhau = FormsAuthentication.HashPasswordForStoringInConfigFile(collection["TaiKhoan.MatKhau"], "md5");

                    //tk.NgheNghiep = collection["TaiKhoan.Job"];
                    //tk.NoiCongTac = collection["TaiKhoan.Location_Job"];

                    //Ok
                    AccountService.Edit(tk);

                    hv.HoTenLienHe = collection["HoTenLienHe"];
                    hv.MoiQuanHe = collection["MoiQuanHe"];
                    hv.DiaChiNguoiLienHe = collection["DiaChiNguoiLienHe"];
                    hv.DienThoaiNguoiLienHe = collection["DienThoaiNguoiLienHe"];
                    hv.EmailNguoiLienHe = collection["EmailNguoiLienHe"];

                    hv.Deleted = int.Parse(collection["Deleted"].ToString());

                    //Ok
                    HocVienService.Edit(hv);

                    //return View(hv);
                    return RedirectToAction("Index", "HocVien", new { area = "Admin" });
                }
                catch(Exception ex)
                {
                    DCS.ComLib.File.Log.Write("HocVienController::Edit", ex.StackTrace, ex.Message);
                    return View();
                }
            }
            //Invalid, redisplay form with errors
            return View("Edit", hv);
        }

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult Delete(int id)
        {
            return View();
        }

        [Authorize(Roles = "Admin,NhanVien")]
        [HttpGet]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                //Get aacount id from hocvien id
                //delete hoc vien id
                //delete account id
                HocVien hv = HocVienService.GetHocVienById(id);
                bool result = HocVienService.DeleteHocVien(id);
                if (result)
                {
                    TaiKhoan tk = AccountService.GetAccountById(hv.MaTaiKhoan.Value);
                    bool r = AccountService.DeleteAccount(tk.MaTaiKhoan);
                    if (r)
                    {
                        return RedirectToAction("Index", "HocVien", new { area = "Admin" });    
                    }
                    else
                    {
                        return View();
                    }
                }
                else
                {
                    return View();
                }
            }
            catch
            {
                return View();
            }
        }
        
        [Authorize(Roles = "Admin,NhanVien")]
        [HttpPost]
        public bool CheckValid(string username)
        {
            if (AccountService.GetAccount(username) != null)
                return false;
            return true;
        }

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult Search()
        {
            return View();
        }

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult SearchResult(string s, string type)
        {
            LMSDataEntities context = new LMSDataEntities();
            var hv = new List<HocVien>();

            if (s != "")
            {
                switch (type)
                {
                    case "tendangnhap":
                        hv = context.HocViens.Where(a => a.TaiKhoan.MaTaiKhoan.Contains(s)).ToList();
                        break;
                    case "hoten":
                        hv = context.HocViens.Where(a => a.TaiKhoan.HoTen.Contains(s)).ToList();
                        break;
                    case "email":
                        hv = context.HocViens.Where(a => a.TaiKhoan.Email.Contains(s)).ToList();
                        break;
                    default:
                        hv = context.HocViens.Where(a => a.TaiKhoan.MaLoaiTaiKhoan == Constant.ACCOUNT_ROLE_STUDENT).ToList();
                        break;
                }
                
            }
            else
            {
                hv = context.HocViens.Where(a => a.TaiKhoan.MaLoaiTaiKhoan == Constant.ACCOUNT_ROLE_STUDENT).ToList();
            }

            HocVienViewModel hvm = new HocVienViewModel(hv, hv.Count());
            return PartialView(hvm);
        }

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult Register()
        {
            int page = 1;
            if (Request["p"] != null)
            {
                page = int.Parse(Request["p"].ToString());
            }

            TaiKhoan account = AccountService.GetTaiKhoanVaLoai(HttpContext.User.Identity.Name);
            HocVien_LopViewModel hocVienList;

            if(account.MaLoaiTaiKhoan == "Admin")
                hocVienList = HocVien_LopService.GetHocVienLopList(int.Parse(ConfigReader.ReadString("ItemPerPage")), page);
            else
                hocVienList = HocVien_LopService.GetHocVienLopList(int.Parse(ConfigReader.ReadString("ItemPerPage")), page, HttpContext.User.Identity.Name);
            
            foreach (HocVien_LopMoRongModel model in hocVienList.ListMoRong)
            {
                model.HV_L.ChuyenDe = (new Converter()).ChuyenDeParser(model.HV_L.ChuyenDe);
            }
            //phân trang
            Pagination pagination = new Pagination(true, Url.Content("~"), "Admin", "HocVien", "Register", "?p=", hocVienList.TotalMoRong, page, int.Parse(ConfigReader.ReadString("ItemPerPage")), "Previous", "Next", "First", "End");
            string pageLinks = pagination.GetPageLinks();
            ViewData["pageLinks"] = pageLinks;
            //end phân trang

            //NHDuc added
            ViewData["page"] = (page - 1) * int.Parse(ConfigReader.ReadString("ItemPerPage")) + 1;
            //end NHDuc

            return View(hocVienList);
        }

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult ChooseClass(int id)
        {
            int page = 1;
            if (Request["p"] != null)
            {
                page = int.Parse(Request["p"].ToString());
            }

            LopHocAvailableViewModel LopHocList = LopHocService.GetLopHocAvailableList(id, int.Parse(ConfigReader.ReadString("ItemPerPage")), page);
            LopHocList.HV.ChuyenDe = (new Converter()).ChuyenDeParser(LopHocList.HV.ChuyenDe);
            LopHocList.HV.HV_L.ThoiGianHoc = (new Converter()).ThoiGianHocParser(LopHocList.HV.HV_L.ThoiGianHoc);

            //phân trang
            Pagination pagination = new Pagination(true, Url.Content("~"), "Admin", "HocVien", "ChooseClass", id + "?p=", LopHocList.Total, page, int.Parse(ConfigReader.ReadString("ItemPerPage")), "Previous", "Next", "First", "End");
            string pageLinks = pagination.GetPageLinks();
            ViewData["pageLinks"] = pageLinks;
            //end phân trang

            //NHDuc added
            ViewData["page"] = (page - 1) * int.Parse(ConfigReader.ReadString("ItemPerPage")) + 1;
            //end NHDuc

            return View(LopHocList); 
        }

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult ChooseThisClass(int hvId, int lopId)
        {
            try
            {
                bool result = HocVien_LopService.UpdateHocVienToLop(hvId, lopId);
                if (result)
                    return RedirectToAction("Detail", "LopHoc", new { area = "Admin", id = lopId });
                return View();
            }
            catch
            {
                return View();
            }
        }

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult ResetPass(int id)
        {
            return View();
        }

        [Authorize(Roles = "Admin,NhanVien")]
        [HttpGet]
        public ActionResult ResetPass(string id)
        {
            try
            {
                HocVien hv = HocVienService.GetHocVienById(int.Parse(id));
                TaiKhoan data = new TaiKhoan();
                data.ID = int.Parse(hv.MaTaiKhoan.ToString());
                data.MatKhau = FormsAuthentication.HashPasswordForStoringInConfigFile("123456", "md5");
                bool result = AccountService.ResetPass(data);
                if (result)
                {
                    return RedirectToAction("Index", "HocVien", new { area = "Admin" });    
                }
                else
                {
                    return View();
                }
            }
            catch (Exception ex)
            {
                return View();
            }
        }

        [Authorize(Roles = "Admin,NhanVien")]
        [HttpGet]
        public ActionResult DeleteRegister(int id)
        {
            try
            {
                bool r = HocVien_LopService.DeleteHocVienLop(id);
                if (r)
                {
                    return RedirectToAction("Register", "HocVien", new { area = "Admin" });
                }
                else
                {
                    return View();
                }
            }
            catch
            {
                return View();
            }
        }

        [Authorize(Roles = "Admin,NhanVien")]
        public ActionResult HocVienThuPhi()
        {
            return View();
        }
    }
}
